package com.sayice.robotconflict.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.sayice.robotconflict.common.result.ApiResult;
import com.sayice.robotconflict.config.JWTConfig;
import com.sayice.robotconflict.dto.req.PlayerReq;
import com.sayice.robotconflict.entity.PlayerEntity;
import com.sayice.robotconflict.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Date;

/**
 * 玩家管理
 *
 * @author shubing
 */
@RestController
@RequestMapping("/player")
public class PlayerController {
    @Autowired
    private PlayerService playerService;
    
    @PostMapping("/register")
    public ApiResult register(@RequestBody @Valid PlayerReq playerReq) {
        playerService.register(playerReq);
        return ApiResult.SUCCESS;
    }
    
    @PostMapping("/login")
    public ApiResult login(@RequestBody PlayerReq playerReq) {
        PlayerEntity playerEntity = playerService.login(playerReq);
        String token = JWT.create().setExpiresAt(Date.from(Instant.now().plus(Duration.ofMinutes(1))))
                .setPayload("id", playerEntity.getId())
                .setKey(JWTConfig.SIGN_SECRET)
                .sign();
        byte[] encryptedBytes = SecureUtil.aes(JWTConfig.TOKEN_SECRET).encrypt(token);
        String encryptedStr = Base64.getUrlEncoder().withoutPadding().encodeToString(encryptedBytes);
        return ApiResult.successOf(encryptedStr);
    }
}
